﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GongZuo.Common;
using GongZuo.Framework;
using GongZuo.Model;

namespace GongZuo.Service.Controllers
{
    public   class PermissionController:BaseController
    {
        /// <summary>
        /// 获取单个权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string Get(int id)
        {
            return Db.Queryable<t_permission>().First(it => it.id == id).JsonSerialize();
        }

        /// <summary>
        /// 权限管理获取所有权限
        /// </summary>
        /// <returns></returns>
        public string GetTreeList()
        {
            var list = GetAllList().Select(it => new {it.id,it.per_id,it.pid,it.per_nm,open=true,it.type }).ToList();
            list.Insert(0, new
            {
                id = (decimal)-1,
                per_id = -1,
                pid = (int?)-2,
                per_nm = "权限列表",
                open=true,
                type=0
            });
            return list.JsonSerialize();
        }

        public string Save(string strModel)
        {
            t_permission permission = strModel.JsonDeserialize<t_permission>();
            ResInfo res = new ResInfo();
            res.state = 0;
            if (0==permission.id)
            {
                int qx_id = Db.Queryable<t_permission>().Max<Int32>(it => it.per_id) + 1;
                permission.per_id = qx_id;
                if (Db.Queryable<t_permission>().Where(it => it.per_nm == permission.per_nm).Count() > 0)
                {
                    res.msg = "权限名重复,请重新添加!";
                }
                else if (Db.Insertable(permission).ExecuteCommand() > 0)
                {
                    res.state = 1;
                    res.msg = "添加成功!";
                }
                else
                {
                    res.msg = "添加失败!";
                }
            }
        }

        /// <summary>
        /// 获取全部权限
        /// </summary>
        /// <returns></returns>
        public static List<t_permission> GetAllList()
        {
            List<t_permission> list = Db.Queryable<t_permission>().OrderBy(it => it.pid).OrderBy(it => it.num).ToList();
            return list;
        }
    }
}
